###
@ngdoc overview
@name xoceanApp
@description
# xoceanApp

Main module of the application.
###
angular.module("xoceanApp", [
  "ngDialog"
  "ui.router"
])

.run ($rootScope, $stateParams, Subject)->
  $rootScope.$on '$stateChangeError', (event, toState, toParams, fromState, fromParams, error)->
    console.log(error)
    return

  $rootScope.$on '$stateChangeStart', (event, toState, toParams, fromState, fromParams)->
    # step_3 out
    if fromState.name is 'xocean.wizard.fillContent'
      window.onbeforeunload = null
    # step_3 in
    if toState.name is 'xocean.wizard.fillContent'
      window.onbeforeunload = null
      window.onbeforeunload = (event)->
        if typeof event == 'undefined'
          event = window.event
        if event
          event.returnValue = '退出将放弃当前正在编辑的专题'
          $rootScope.$broadcast('quit')
        
        return '退出将放弃当前正在编辑的专题'

    if fromState.name is 'xocean.wizard.fillContent' and toState.name isnt 'xocean.wizard.basicInfo' and toState.name isnt 'xocean.wizard.finish'
      if not window.confirm('确认放弃正在编辑的专题吗？')
        event.preventDefault()
      else
        $rootScope.$broadcast('quit')
    return

.config ($stateProvider, $urlRouterProvider)->

  $urlRouterProvider
    .otherwise("//home");

  $stateProvider.state 'xocean',
    url: '/:topicid'
    abstract: true
    template: "<div ui-view></div>"
    controller: ['$rootScope', '$state', '$stateParams', '$window', ($rootScope, $state, $stateParams, $window)->
      channelConfig = {
        '0001': 'news'
        '0003': 'ent'
        '0004': 't'
        '0005': 'sports'
        '0006': 'travel'
        '0007': 'house'
        '0008': 'auto'
        '0009': 'tech'
        '0010': 'home'
        '0011': 'mobile'
        '0016': 'digi'
        '0023': 'gov'
        '0025': 'money'
        '0026': 'lady'
        '0029': 'edu'
        '0030': 'tie'
        '0031': 'game'
        '0036': 'baby'
        '0082': 'jiu'
        '0085': 'v'
        '0087': 'gz.house'
        '0091': 'daxue'
        '0092': 'book'
        '0093': 'gongyi'
        '0095': 'men'
      }
      $rootScope.$state = $state
      $rootScope.$stateParams = $stateParams
      $rootScope.TOPICID = $stateParams.topicid
      $rootScope.CHANNELID = $rootScope.TOPICID.slice(0, 4) or '0001'
      $rootScope.CHANNELDOMAIN = channelConfig[$rootScope.CHANNELID]
      $window.TOPICID = $rootScope.TOPICID
      $window.CHANNELID = $rootScope.CHANNELID
      $window.CHANNELDOMAIN = $rootScope.CHANNELDOMAIN
      if not $rootScope.TOPICID
        alert('topicid缺失！请确保URL的形式为/#/topicid/...')
      console.log $stateParams
    ]
    
  .state 'xocean.home',
    url: '/home'
    templateUrl: "views/main.html"
    controller: 'MainCtrl'
    resolve: {
      templates: ['Template', (Template)->
        return Template.getTemplates()
      ]
    }
  .state 'xocean.subjects',
    url: '/subjects'
    templateUrl: 'views/subjects.html'
    controller: 'SubjectsCtrl'
    resolve: {
      publishedSubjects: ['Subject', (Subject)->
        return Subject.getPublishedSubjects()
      ]
    }
  .state 'xocean.templates',
    url: '/templates'
    templateUrl: 'views/templates.html'
    controller: 'TemplatesCtrl'
    resolve: {
      templates: ['Template', (Template)->
        return Template.getTemplates()
      ]
    }
  .state 'xocean.wizard',
    abstract: true
    url: '/wizard?subjectId&newFromSubject&templateId&newFromTemplate'
    templateUrl: 'views/newsubject.html'
    controller: 'NewSubjectCtrl'
    resolve: {
      subject: ['$stateParams', 'Subject', ($stateParams, Subject) ->
        id = $stateParams.subjectId or $stateParams.newFromSubject or ''
        return null unless id
        return Subject.getSubjectById(id)
      ]
      template: ['$stateParams', 'Template', ($stateParams, Template) ->
        id = $stateParams.templateId or $stateParams.newFromTemplate or ''
        return null unless id
        return Template.getTemplateById(id)
      ]
    }
  .state 'xocean.wizard.chooseTmpl',
    url: '/step_1'
    templateUrl: 'views/partials/step_1.html'
    resolve: {
      templates: ['Template', (Template)->
        return Template.getTemplates()
      ]
    }
    controller: ['$scope','$state', 'Template', 'templates', ($scope, $state, Template, templates)->
      $scope.$parent.selectedTmpl = null
      $scope.$parent.html = ''
      $scope.$parent.basicInfo = {
        modelid: ''
        modelname: ''
        timeout: 0
        freq: 0
        keywords: ''
        digest: ''
        thumbnail: ''
      }

      $scope.templates = templates
      $scope.selectTmpl = (tmpl)->
        Template.addOne(tmpl.id).then (data)->
          if data.data.result is 1
            console.log 'AddOne'
        Template.getTemplateById(tmpl.id).then (data)->
          $scope.$parent.selectedTmpl = tmpl
          $scope.$parent.html = data.html unless $scope.$parent.html
          $scope.$parent.basicInfo.thumbnail = tmpl.thumbnail
          return
        return

      $scope.resetTmpl = ->
        $scope.$parent.selectedTmpl = null
        $scope.$parent.html = ''
        return
      return


    ]

  .state 'xocean.wizard.basicInfo',
    url: '/step_2'
    templateUrl: 'views/partials/step_2.html'
    controller: ['$scope', 'Template', 'Subject', '$location', '$state', ($scope, Template, Subject, $location, $state)->
      $state.go('xocean.wizard.chooseTmpl') unless $scope.selectedTmpl or $scope.html

      # modelid_backup 是不带频道号的modelid 例如： hehe_vs
      # modelid 为带频道号的modelid 例如： 0001hehe_vs
      if $scope.$parent.basicInfo.modelid_backup
        $scope.$parent.basicInfo.modelid = $scope.$parent.basicInfo.modelid_backup
      $scope.submitBasicInfo = (form)->
        if form.$valid
          Subject.saveBasicInfo($scope.basicInfo).then (data)->
            if +data.result is 1
              $scope.$parent.basicInfo = $scope.basicInfo
              $scope.$parent.basicInfo.modelid_backup = $scope.$parent.basicInfo.modelid
              $scope.$parent.basicInfo.modelid = data.modelid
              $state.go('xocean.wizard.fillContent')
            else
              alert(data.msg) if data.msg
        else
          $scope.basicInfo.submitted = true
      return
    ]

  .state 'xocean.wizard.fillContent',
    url: '/step_3'
    templateUrl: 'views/partials/step_3.html'
    controller: ['$scope','$state', 'Subject', ($scope, $state, Subject)->
      $state.go('xocean.wizard.chooseTmpl') unless $scope.selectedTmpl or $scope.html
      $state.go('xocean.wizard.basicInfo') unless $scope.basicInfo.modelid
      return
    ]
  .state 'xocean.wizard.finish',
    url: '/step_4'
    templateUrl: 'views/partials/step_4.html'
    controller: ['$scope','$state', ($scope, $state)->
      $state.go('xocean.wizard.chooseTmpl') unless $scope.selectedTmpl or $scope.html
      return
    ]
  return

.config ($httpProvider)->
  $httpProvider.defaults.transformRequest = (obj)->
   str = []
   for key,value of obj
     str.push(encodeURIComponent(key) + "=" + encodeURIComponent(value))
   return str.join("&")
  $httpProvider.defaults.headers.post = {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  return


